//
//  SHOAuthViewController.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/24.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

class SHOAuthViewController: UIViewController {
    
    //MARK: - 懒加载控件
    private lazy var webView: SHOAuthWebView = SHOAuthWebView()
    private lazy var progressView: SHOAuthProgressView = SHOAuthProgressView()
    
    //MARK: - 设置界面
    override func loadView() {
        view = webView
        
        webView.delegate = self
        webView.backgroundColor = UIColor.whiteColor()
        
        setupNav(false)

    }
    //MARK: -设置导航栏界面
    func setupNav(isLogin: Bool) {
        if isLogin {
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "didClickCancel")
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", target: nil, action: nil)
            return
        }
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "didClickCancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "didClickAutoFill")
    }
    
    //MARK: - 监听事件
    @objc private func didClickCancel() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func didClickAutoFill() {
        let jsString = "document.getElementById('userId').value='\(K_WB_NAME)',document.getElementById('passwd').value='\(K_WB_PASSWD)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}

//MARK: - Delegate
extension SHOAuthViewController:UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        //加载进度条视图
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
        progressView.startAnimating()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //移除进度条视图
        progressView.endAnimating()
        progressView.removeFromSuperview()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print(error)
    }
    
    //监听webView 将要加载request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //请求的url字符串
        let urlString = request.URL?.absoluteString
        
        if let _urlString = urlString where _urlString.hasPrefix(K_APPREDIRECT_URI) {
            //url的请求参数
            let query = request.URL?.query
            //截取字符串中的code
            if let _query = query {
                let code = _query.substringFromIndex("code=".endIndex)
                
                print(code)
                
                SHUserAccountViewModel.sharedTools.loadUserAccount(code, succeed: { (succ) -> () in
                    //更新导航栏
                    self.setupNav(true)
                    
                    if !succ {
                        print("请求失败")
                        return
                    }
                    // 先关闭当前界面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 发送一个通知 告知appdelegate 切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                    })
             
                })
                return false
            }
        }
        
        return true
    }
}






